#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from fastapi import Depends, FastAPI

from apps.routers import api_router
from common.log import set_customize_logfile, setup_logging
from core.conf import settings
from core.path_conf import STATIC_DIR

from utils.health_check import ensure_unique_route_names
from utils.openapi import simplify_operation_ids
from fastapi_pagination import add_pagination


def register_app():
    # FastAPI
    app = FastAPI(
        title=settings.TITLE,
        version=settings.VERSION,
        description=settings.DESCRIPTION,
        docs_url=settings.DOCS_URL,
        # redoc_url=settings.REDOCS_URL,
        # openapi_url=settings.OPENAPI_URL,
    )

    # 日志
    register_logger()

    # 静态文件
    register_static_file(app)

    # 中间件
    register_middleware(app)

    # 路由
    register_router(app)

    # 分页
    register_page(app)

    return app


def register_logger() -> None:
    """
    系统日志

    :return:
    """
    setup_logging()
    set_customize_logfile()


def register_static_file(app: FastAPI):
    """
    静态文件交互开发模式, 生产使用 nginx 静态资源服务

    :param app:
    :return:
    """
    if settings.STATIC_FILES:
        import os

        from fastapi.staticfiles import StaticFiles

        if not os.path.exists(STATIC_DIR):
            os.mkdir(STATIC_DIR)
        app.mount('/static', StaticFiles(directory=STATIC_DIR), name='static')


def register_middleware(app: FastAPI):
    """
    中间件，执行顺序从下往上

    :param app:
    :return:
    """
    # Opera log
    # app.add_middleware(OperaLogMiddleware)
    # # JWT auth, required
    # app.add_middleware(
    #     AuthenticationMiddleware, backend=JwtAuthMiddleware(), on_error=JwtAuthMiddleware.auth_exception_handler
    # )
    # Access log
    if settings.MIDDLEWARE_ACCESS:
        from middleware.access_middleware import AccessMiddleware
        app.add_middleware(AccessMiddleware)

    # CORS: Always at the end
    if settings.MIDDLEWARE_CORS:
        from fastapi.middleware.cors import CORSMiddleware

        app.add_middleware(
            CORSMiddleware,
            allow_origins=['*'],
            allow_credentials=True,
            allow_methods=['*'],
            allow_headers=['*'],
        )

    # if settings.MIDDLEWARE_AUTH:
    #     from middleware.access_middleware import UserAgentEncryptionMiddleware
    #     app.add_middleware(UserAgentEncryptionMiddleware)


def register_router(app: FastAPI):
    """
    路由

    :param app: FastAPI
    :return:
    """
    dependencies = None

    # API
    app.include_router(api_router, dependencies=dependencies)

    # Extra
    ensure_unique_route_names(app)
    simplify_operation_ids(app)


def register_page(app: FastAPI):
    """
    分页查询

    :param app:
    :return:
    """
    add_pagination(app)
